package dfbz.com.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    public BaseServlet() {
        super();
    }

    /**
     * 通过请求路径接口名字找到对应的方法，并执行该方法：
     * 如/user/login 则执行user接口里的login方法
     *
     * 代理执行**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        uri = uri.replace(req.getContextPath(),"");
        System.out.println("servlet请求的url(方法名字)："+uri);
        String[] split = uri.split("/");

        Class<? extends BaseServlet> servletClass = this.getClass();
        String className = servletClass.getName();


        try {

            Class<?> aClass = Class.forName(className);

            Object obj = aClass.newInstance();
            //重点看看这个方法名对不对
            String methodName = split[2];
            System.out.println("方法名为："+methodName);
            //通过反射，找到方法，代理执行这个方法
            Method method = aClass.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(obj,req,resp);
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
}
